import axios from 'axios'
import store from '@/store'
import router from '../router'
import { Message, Notice, Modal } from 'view-design'

// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const {
    statusText,
    status,
    request: { responseURL }
  } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        Authorization: 'Bearer ' + store.state.user.token
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url)
        const { data, status } = res
        if (data.code === 401 && (window.location.pathname == '/index' || window.location.pathname != '/login')) {
          return false;
        } else if (data.code === 401 ) {
          Modal.confirm({
            title: '系统提示',
            content: '<p>你的账号已被登出，请重新进行登录</p >',
            okText: '重新登录',
            cancelText: '取消',
            onOk: () => {
              store.dispatch('handleLogOut').then(() => {
                location.reload() // 为了重新实例化vue-router对象 避免bug
              })
            },
            onCancel: () => {}
          })
        } else if (data.code === 403) {
          let message = '很抱歉，您没有权限进行操作'
          Notice.warning({
            name: 'sys',
            title: '系统提示',
            desc: message,
            duration: 3
          })
        } else if (data.code >= 500 && data.code < 600) {
          let message = '很抱歉，服务器出错啦'
          Notice.error({
            name: 'sys',
            title: '系统提示',
            desc: message,
            duration: 3
          })
        } else if (data.code >= 400 && data.code < 500) {
          Notice.error({
            name: 'sys',
            title: '系统提示',
            desc: data.message,
            duration: 3
          })
        }
        return {
          data,
          status
        }
      },
      error => {
        this.destroy(url)
        let errorInfo = error.response
        if (errorInfo) {
          const {
            response: { statusText, status, data },
            config
          } = JSON.parse(JSON.stringify(error))
          errorInfo = {
            statusText,
            status,
            data,
            request: {
              responseURL: config.url
            }
          }
        }
        // addErrorLog(errorInfo)
        return Promise.reject(error)
      }
    )
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
